﻿@page "/"
@using EFCore_Dbcontext.Models;
@using Data
@using AntDesign.TableModels
@using System.Text.Json
@using System.Text.Json.Serialization
@inject IZsg Help;
@inject IHttpClientFactory ClientFactory
<PageTitle>Index</PageTitle>

@*
<Table1 Items="Data" Pagedisplay="false">
    <Header>
    <th>编号</th>
    <th>名字</th>
    <th>类型</th>
    <th>年龄</th>
    <th>价格</th>
    <th>操作</th>
    </Header>
    <Row>
        <td>@context.Id </td>   <td>@context.Name </td>   <td>@context.Type?.Name </td>   <td>@context.Age </td>    <td>@context.Price </td>
        <td><Button Type="primary">编辑</Button><Button Danger Type="primary">删除</Button> </td>
     </Row>

 </Table1>
 <Page onChange="onChange" PageChanged="hand" PageNumber="PageIndex" PagesSize="Size" PagesCount="Count" /> *@
<div>
    <div class="row">
        <Space Size="@("100")">
            <SpaceItem>
                <Button OnClick="addRow" disabled="@btndisabled" Type="primary" Style="margin-bottom:16px">
                    添加一行
                </Button>
            </SpaceItem>

            <SpaceItem Style="width:70%">

                <label style="padding-right:10px; font-weight:700;">查询名称:</label>
                <Input Type="text" @bind-Value="Query" Style="width:60%;" />

                <Select TItem="string"
                        TItemValue="int"
                        @bind-Value="_Select"
                        Style="width:20%;"
                        OnSelectedItemChanged="GetQueryMethod"
                        DefaultValue="0">
                    <SelectOptions>
                        <SelectOption TItem="string" TItemValue="int" Value="@(0)" Label="全部"></SelectOption>
                        @foreach (var item in _CType)
                        {
                            <SelectOption TItem="string" TItemValue="int" Value="@item.Id" Label="@item.Name"></SelectOption>
                        }
                    </SelectOptions>
                </Select>
                <Button OnClick="GetQueryMethod" Type="primary" Style="margin-bottom:16px;margin-left:20px">
                    查询
                </Button>
                <ToExcel Items="Data"></ToExcel>
            </SpaceItem>
        </Space>
    </div>
    <Table TItem="Yuan"
           DataSource="@Data"
           Total="Count"
           @bind-PageIndex="PageIndex"
           @bind-PageSize="Size"
           Size="TableSize.Small"
           OnChange="onChange"
           RowKey="x=>x.Id">
        <Selection Key="@(context.Id.ToString())" />
        <PropertyColumn Property="c=>c.Id" Sortable Filterable />

         <PropertyColumn Property="c=>c.Name" Sortable Filterable>
            @if (editId == context.Id)
            {
                <Input Type="text" @bind-Value="context.Name" AutoFocus />
            }
            else
            {
                <div class="editable-cell-value-wrap" style="padding-right:24px">
                    @context.Name
                </div>
            }
        </PropertyColumn>
        <PropertyColumn Property="c=>c.Age" Sortable Filterable>
            @if (editId == context.Id)
            {
                <Input Type="text" @bind-Value="context.Age" AutoFocus />
            }
            else
            {
                <div class="editable-cell-value-wrap" style="padding-right:24px">
                    @context.Age
                </div>
            }

        </PropertyColumn>
        <PropertyColumn Property="c=>c.Typeid" Sortable>
            @if (editId == context.Id)
            {
                <Select TItem="CType"
                        TItemValue="int"
                        DataSource="@_CType"
                        @bind-Value="@(context.Typeid)"
                        ValueName="@nameof(CType.Id)"
                        LabelName="@nameof(CType.Name)">
                </Select>
            }
            else
            {
                <div class="editable-cell-value-wrap" style="padding-right:24px">
                    @GetName(context.Typeid)
                </div>
            }

        </PropertyColumn>
        <PropertyColumn Property="c=>c.Price" Sortable Filterable>
            @if (editId == context.Id)
            {
                <Input Type="text" @bind-Value="context.Price" AutoFocus />
            }
            else
            {
                <div class="editable-cell-value-wrap" style="padding-right:24px">
                    @context.Price
                </div>
            }
        </PropertyColumn>
        <ActionColumn Title="操作">
            @if (editId == context.Id)
            {
                <Space>
           
                    <SpaceItem><Button Type="primary" OnClick="()=>stopEdit(true)">确认</Button></SpaceItem>
                    <SpaceItem><Button Danger OnClick="()=>stopEdit(false)">取消</Button></SpaceItem>
                 </Space>
            }
            else
            {
                <Space>
                    <SpaceItem><Button Type="primary" @onclick="()=>startEdit(context.Id,context)">编辑</Button></SpaceItem>
                    <SpaceItem>
                        <Popconfirm Title="删除吗"
                                    OnConfirm="() => Delete(context.Id)"
                                    CancelText="No"
                                    OkText="Yes">

                            <Button Danger>删除</Button>
                     </Popconfirm>
                 </SpaceItem>
             </Space>

            }

        </ActionColumn>
    </Table>
</div>

@code {
    bool btndisabled = false;
    int Size = 20, PageIndex = 1, Count = 20, _Select;
    int editId = -1;
    string successMessage = string.Empty, StrErr = string.Empty, Query = string.Empty;
    List<Yuan> Data = new List<Yuan>();
    List<CType> _CType = new List<CType>();
    Yuan _Yuan = new Yuan();
  

    async Task stopEdit(bool save)
    {
        var client = ClientFactory.CreateClient();
        if (!save)
        {
            successMessage = "操作取消";
            Help.ShowMess(successMessage, EShowMess.Info);
        }
        else
        {
           
            HttpResponseMessage result;
            if (editId == 0)
                result = await client.PostAsJsonAsync("C_USER/Add", _Yuan);
            else
                result = await client.PutAsJsonAsync("C_USER/Put", _Yuan);

            if (result.IsSuccessStatusCode)
            {
                successMessage = (editId == 0) ? "添加成功！" : "修改成功！";
                Help.ShowMess(successMessage, EShowMess.Success);
            }
            else
            {
                successMessage = (editId == 0) ? "添加失败！" : "修改失败！";
                Help.ShowMess(successMessage, EShowMess.Error);
            }
        }

        await LoadData(); // 无论是保存还是取消，都需要重新加载数据
        btndisabled = false;

        editId = -1;
    }
    async Task GetQueryMethod()
    {
        var client = ClientFactory.CreateClient();

        var result = await client.GetFromJsonAsync<_Models<Yuan>>("C_USER/GetList"
        .API($"pageNumber={PageIndex}&pageSize={Size},ItName={Query},SelZL={(_Select == 0 ? 0 : 1)},TYPEid={_Select}"));

        if (result != null)
        {
            Count = result.TotalItems;
            Data = result.Data;
        }
    }
    string GetName(int id)
    {
        return _CType.SingleOrDefault(d => d.Id == id)?.Name ?? "";
    }
    void addRow()
    {
        btndisabled = true;
        editId = 0;
        Data.Add(_Yuan);

    }
    void startEdit(int id, Yuan mode)
    {
        btndisabled = true;
        editId = id;
        _Yuan = mode;
    }
    private async Task Delete(int id)
    {

        var client = ClientFactory.CreateClient();
        var result = await client.DeleteAsync("C_USER/Del".API(id.ToString()));


        if (result.IsSuccessStatusCode)
        {
            Data.Remove(Data.First(d => d.Id == id));
            successMessage = "删除成功";
            Help.ShowMess(successMessage, EShowMess.Success);
        }
        else
        {
            successMessage = "删除失败";
            Help.ShowMess(successMessage, EShowMess.Error);
        }



    }
    async Task LoadData()
    {
        try
        {
            _Yuan = new Yuan();
            var client = ClientFactory.CreateClient();
            var result = await client.GetFromJsonAsync<_Models<Yuan>>($"C_USER/GetList".API($"pageNumber={PageIndex},pageSize={Size}"));

            if (result != null)
            {
                Count = result.TotalItems;
                Data = result.Data;
                _CType = result.TypeItme;
            }

        }

        catch (Exception e)
        {
            Help.ShowMess(e.Message, EShowMess.Error);
        }
    }
    protected override async Task OnInitializedAsync()
    {


        try
        {

            await LoadData();
        }
        catch (Exception e)
        {
            Help.ShowMess(successMessage, EShowMess.Error);
        }

        // Data = Help.GetList<Yuan>
        //(ref Count, PageIndex, Size);
        // var json = await Help.GetList<Yuan>
        // (PageIndex, Size);
        // var result =JsonConvert.DeserializeObject<Model<Yuan>>(json);


        // 获取总记录数和当前页的数据
        // Count = result!.Count;
        // Data = result._Model;

    }

    public async Task onChange(QueryModel<Yuan> query)
    {
        await LoadData();
        if (query.SortModel != null && query.SortModel.Count > 0)
        {
            var sortedData = Data.AsQueryable();

            foreach (var sortField in query.SortModel)
            {
                var fieldName = sortField.FieldName;
                var sortDirection = sortField.Sort;

                // 根据排序字段和排序方向对数据进行排序
                if (sortDirection == "ascend")
                {
                    sortedData = sortedData.OrderBy(d => GetPropertyValue(d, fieldName));
                }
                else if (sortDirection == "descend")
                {
                    sortedData = sortedData.OrderByDescending(d => GetPropertyValue(d, fieldName));
                }
            }

            Data = sortedData.ToList();
        }
        if (query.FilterModel != null && query.FilterModel.Count > 0)
        {
            var filteredData = Data.AsQueryable();

            foreach (var filterField in query.FilterModel)
            {
                var fieldName = filterField.FieldName;
                var filterValue = filterField.Filters;
                foreach (var item in filterValue)
                {
                    if (item.FilterCompareOperator == TableFilterCompareOperator.Equals)
                    {
                        filteredData = filteredData.Where(d => GetPropertyValue(d, fieldName).ToString().Contains(item.Value.ToString()));
                    }
                    else if (item.FilterCompareOperator == TableFilterCompareOperator.GreaterThan)
                    {
                        filteredData = filteredData.Where(d => Convert.ToInt32(GetPropertyValue(d, fieldName)) > Convert.ToInt32(item.Value));
                    }
                    else if (item.FilterCompareOperator == TableFilterCompareOperator.LessThan)
                    {
                        filteredData = filteredData.Where(d => Convert.ToInt32(GetPropertyValue(d, fieldName)) < Convert.ToInt32(item.Value));
                    }
                    else if (item.FilterCompareOperator == TableFilterCompareOperator.NotEquals)
                    {
                        filteredData = filteredData.Where(d => !GetPropertyValue(d, fieldName).ToString().Contains(item.Value.ToString()));
                    }
                    else if (item.FilterCompareOperator == TableFilterCompareOperator.GreaterThanOrEquals)
                    {
                        filteredData = filteredData.Where(d => Convert.ToInt32(GetPropertyValue(d, fieldName)) >= Convert.ToInt32(item.Value));
                    }
                    else if (item.FilterCompareOperator == TableFilterCompareOperator.LessThanOrEquals)
                    {
                        filteredData = filteredData.Where(d => Convert.ToInt32(GetPropertyValue(d, fieldName)) <= Convert.ToInt32(item.Value));
                    }
                    else if (item.FilterCompareOperator == TableFilterCompareOperator.Contains)
                    {
                        filteredData = filteredData.Where(d => GetPropertyValue(d, fieldName).ToString().Contains(item.Value.ToString()));

                    }

                }
                // 根据过滤字段和过滤值对数据进行过滤

            }
            Data = filteredData.ToList();
            // 现在 filteredData 包含了根据过滤条件过滤后的数据
        }
    }

    private object GetPropertyValue(Yuan obj, string propertyName)
    {
        var propertyInfo = typeof(Yuan).GetProperty(propertyName);
        return propertyInfo.GetValue(obj);
    }


}

